import * as express from "express"
import { Request, Response } from "express"
import { Application, getLogger } from "pinus";
import { Code } from "../../../consts/code";
import { BackendSession } from "pinus/lib/index";
import * as crypto from "crypto";
import { Token } from "../../../util/token";
const logger = getLogger("http-log")

module.exports = function (app: Application, http: express.Application) {
    const key = app.get('http').key

    /**
    * 用户登录  任何页面(比如大厅)点击游戏  需要带一个id过来，区别用户
    */
    http.post('/api/login', async (request: Request, response: Response) => {
        let uid = request.body.uid//玩家id
        // 创建签名
        let tokenStr = Token.create(uid)
        // let url = 'http://127.0.0.1?'
        return response.end(JSON.stringify({ code: Code.OK, data: { token: tokenStr } }))
    })
    /**
    *  获取游戏入口及Token
    */
    http.post('/api/geturl', async (request: Request, response: Response) => {

        let values = {
            channel_id: request.body.channelId,//渠道id
            username: request.body.username,//名称
            currency: request.body.currency,//币种
            currencyNum: request.body.currencyNum,//币种数量
            expand: request.body.expand//1:一般用户  2:测试用户
        }
        //判断用户是否存在(如果 进入过 游戏 会添加记录)
        //如果不存在  创建用户
        const aviatorServers = app.getServersByType('aviator')//选择服务地址
        let uid = await app.rpc.aviator.remote.haveUserBychannelId.toServer(aviatorServers[0].id, values)

        // 创建签名
        let tokenStr = Token.create(uid.toString())
        let http_address = await app.rpc.aviator.remote.getGameClientUrl.toServer(aviatorServers[0].id)
        //拼接地址
        let Url = http_address + '?sign=' + tokenStr
        return response.end(JSON.stringify({ code: Code.OK, data: { token: Url } }))
    })

    /*
    *   踢玩家下线 
    */
    http.post('/control/kick', async (request: Request, response: Response) => {
        let sign = request.body.sign
        let timestamp = request.body.timestamp
        let userId = request.body.userId
        if (!sign || !timestamp || !userId) {
            return response.end(JSON.stringify({ code: Code.ERROR_PARAM }))
        }
        // 验签
        let signStr = 'timestamp=' + timestamp + '&userId=' + userId + '&key=' + key
        if (sign !== crypto.createHash('md5').update(signStr).digest('hex')) {
            return response.end(JSON.stringify({ code: Code.INVALID_TOKEN }))
        }
        const connector = app.getServersByType('connector')
        let backendSessionService = app.backendSessionService
        let sessions: BackendSession[] = await backendSessionService.agetByUid(connector[0].id, userId.toString())
        // 玩家不在线
        if (!sessions || sessions.length !== 1) {
            return response.end(JSON.stringify({ code: Code.USER_NOT_ONLINE }))
        }
        await backendSessionService.akickByUid(connector[0].id, userId)
        return response.end(JSON.stringify({ code: Code.OK }))
    })

    /*
    * 停止游戏
    */
    http.post('/control/stopGame', async (request: Request, response: Response) => {
        let sign = request.body.sign
        let timestamp = request.body.timestamp
        let userId = request.body.userId
        if (!sign || !timestamp) {
            return response.end(JSON.stringify({ code: Code.ERROR_PARAM }))
        }
        // 验签
        let signStr = 'timestamp=' + timestamp + '&key=' + key
        if (sign !== crypto.createHash('md5').update(signStr).digest('hex')) {
            return response.end(JSON.stringify({ code: Code.INVALID_TOKEN }))
        }
        const aviatorServers = app.getServersByType('aviator')
        // 停止游戏
        await app.rpc.aviator.remote.stopGame.toServer(aviatorServers[0].id)
        return response.end(JSON.stringify({ code: Code.OK }))
    })

    /*
    * 踢出所有玩家
    */
    http.post('/control/kickAll', async (request: Request, response: Response) => {
        let sign = request.body.sign
        let timestamp = request.body.timestamp
        if (!sign || !timestamp) {
            return response.end(JSON.stringify({ code: Code.ERROR_PARAM }))
        }
        // 验签
        let signStr = 'timestamp=' + timestamp + '&key=' + key
        if (sign !== crypto.createHash('md5').update(signStr).digest('hex')) {
            return response.end(JSON.stringify({ code: Code.INVALID_TOKEN }))
        }
        const aviatorServers = app.getServersByType('aviator')
        // 踢出所有玩家
        await app.rpc.aviator.remote.kickAll.toServer(aviatorServers[0].id)
        return response.end(JSON.stringify({ code: Code.OK }))
    })

    /*
    * 后台结算
    */
    http.post('/control/cashOut', async (request: Request, response: Response) => {
        let sign = request.body.sign
        let timestamp = request.body.timestamp
        let roundId = request.body.roundId
        let operatorId = request.body.operatorId
        if (!sign || !timestamp || !roundId || !operatorId) {
            return response.end(JSON.stringify({ code: Code.ERROR_PARAM }))
        }
        // 验签
        let signStr = 'operatorId=' + operatorId + '&roundId=' + roundId + '&timestamp=' + timestamp + '&key=' + key
        if (sign !== crypto.createHash('md5').update(signStr).digest('hex')) {
            return response.end(JSON.stringify({ code: Code.INVALID_TOKEN }))
        }
        const aviatorServers = app.getServersByType('aviator')
        // 强制结算
        const result = await app.rpc.aviator.remote.forceEnd.toServer(aviatorServers[0].id, parseInt(roundId), parseInt(operatorId))
        return response.end(JSON.stringify({ code: result }))
    })

    /*
    * 给用户上分
    */
    http.post('/control/addCoin', async (request: Request, response: Response) => {
        const sign = request.body.sign
        const timestamp = request.body.timestamp
        const userId = request.body.userId
        const addCoin = request.body.addCoin
        if (!userId || !sign || !timestamp || !addCoin) {
            return response.end(JSON.stringify({ code: Code.ERROR_PARAM }))
        }
        // 验签
        const signStr = 'userId=' + userId + '&addCoin=' + addCoin + '&timestamp=' + timestamp + '&key=' + key
        if (sign !== crypto.createHash('md5').update(signStr).digest('hex')) {
            return response.end(JSON.stringify({ code: Code.INVALID_TOKEN }))
        }
        const aviatorServers = app.getServersByType('aviator')
        const result = await app.rpc.aviator.remote.increaseCoin.toServer(aviatorServers[0].id, parseInt(userId), parseInt(addCoin))
        return response.end(JSON.stringify({ code: result }))
    })

    /*
    * 给用户下分
    */
    http.post('/control/decreaseCoin', async (request: Request, response: Response) => {
        const sign = request.body.sign
        const timestamp = request.body.timestamp
        const userId = request.body.userId
        const coin = request.body.coin
        if (!userId || !sign || !timestamp || !coin) {
            return response.end(JSON.stringify({ code: Code.ERROR_PARAM }))
        }
        // 验签
        const signStr = 'userId=' + userId + '&coin=' + coin + '&timestamp=' + timestamp + '&key=' + key
        if (sign !== crypto.createHash('md5').update(signStr).digest('hex')) {
            return response.end(JSON.stringify({ code: Code.INVALID_TOKEN }))
        }
        const aviatorServers = app.getServersByType('aviator')
        const result = await app.rpc.aviator.remote.decreaseCoin.toServer(aviatorServers[0].id, parseInt(userId), parseInt(coin))
        return response.end(JSON.stringify({ code: result }))
    })
}
